from . import config
import wmi
import hashlib

client_config=config.client_config
class MachineCodeGenerator:
    def __init__(self):
        self.pre_str = client_config["pre_str"]
        self.suf_str = client_config["suf_str"]

        # 获取机器码，机器码由以下四部分拼接组成
        # 1、CPU序列号  2、MAC地址 3.硬盘序列号 4.主板序列号
        self.m_wmi = wmi.WMI()

    # cpu序列号 16位
    def get_cpu_serial(self):
        cpu_info = self.m_wmi.Win32_Processor()
        if len(cpu_info) > 0:
            serial_number = cpu_info[0].ProcessorId
            return serial_number
        else:
            return "ABCDEFGHIJKLMNOP"

    # 硬盘序列号 15位
    def get_disk_serial(self):
        try:
            disk_info = self.m_wmi.Win32_PhysicalMedia()
            disk_info.sort()
            if len(disk_info) > 0:
                serial_number = disk_info[0].SerialNumber.strip()
                return serial_number
            else:
                return "WD-ABCDEFGHIJKL"
        except Exception as e:
            return "WD-ABCDEFGHIJKL"

    # mac地址 12位
    def get_mac_address(self):
        for network in self.m_wmi.Win32_NetworkAdapterConfiguration():
            mac_address = network.MacAddress
            if mac_address != None:
                return mac_address.replace(":", "")
        return "ABCDEF123456"

    # 主板序列号 14位
    def get_board_serial(self):
        board_info = self.m_wmi.Win32_BaseBoard()
        if len(board_info) > 0:
            board_id = board_info[0].SerialNumber.strip().strip('.')
            return board_id
        else:
            return "ABCDEFGHIJKLMN"

    # 拼接生成机器码
    def getMachineCode(self):
        mac_address = self.get_mac_address()
        cpu_serial = self.get_cpu_serial()
        disk_serial = self.get_disk_serial()
        board_serial = self.get_board_serial()

        combine_str = self.pre_str + mac_address + cpu_serial + \
            disk_serial + board_serial + self.suf_str
        combine_byte = combine_str.encode("utf-8")
        machine_code = hashlib.md5(combine_byte).hexdigest()
        return machine_code.upper()